package com.demo.interceptor;

import com.demo.tool.JWTUTIL;
import com.demo.tool.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.io.IOException;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private Token tokenTool;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //默认设置验证失败
        Boolean flag=false;

        //获取请求头部携带的token
       String Token=request.getHeader("Authorization");
       if(!StringUtils.hasLength(Token)||Token.isEmpty()){
           responseJson(response,"token为空");
       }else {
           //验证是否存在本地redis中 验证秘钥是否一致 解析正常
          if(tokenTool.verifyAndRefreshUserToken(Token)){
              //通过了验证
              flag=true;
          }else {
              responseJson(response,"token失效,请重新登录");
          }

       }


        return flag;
    }


    //设置请头类型 以及返回信息
    private void responseJson(HttpServletResponse response, String message) {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(404);
        try {
            response.getWriter().write(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
